layui.use(['form','tree','element','table','laytpl','treeGrid','layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;

    //获取路径参数
    var request = GetRequest();
    window.selected = null;

    //生产管理
    var height = $(document).height();
    $("#table-content").css("height",(height - 40) + "px");
    $(window).on("resize",function () {
        $(".table-content").css('height',(height - 40) + "px");
    });

    //加载生产环节信息
    var treeData = {
        elem: '#process-tree' //指定元素
        , target: '_blank' //是否新选项卡打开（比如节点返回href才有效）
        , click: function (item) { //点击节点回调
            $("#tips").hide();
            window.selected = item;
            //列表数据
            var option = {
                elem: '#tableList',
                url : '/process/qrcode/query?produceBatchId=' + request.id + '&processId=' + item.id,
                cellMinWidth : 95,
                page : true,
                height : "full-125",
                limits : [10,15,20,25],
                limit : 15,
                id : "listTable",
                cols : [[
                    {type: "checkbox", fixed:"left", width:50},
                    {field: 'name', title: '名称', minWidth:100, align:"center"},
                    {field: 'requestUrl', title: '请求接口', minWidth:100, align:"center"},
                    {field: 'fieldId', title: '地块', minWidth:100, align:"center", templet:function(d){
                            var name = null;
                            $.ajax({
                                url:"/field/"+d.fieldId,
                                type:'GET',
                                async:false,
                                success:function (data){
                                    name = data.name;
                                }
                            });
                            return name;
                        }},
                    {field: 'personId', title: '负责人', minWidth:100, align:"center", templet:function(d){
                            var name = null;
                            $.ajax({
                                url:"/person/"+d.personId,
                                type:'GET',
                                async:false,
                                success:function (data){
                                    name = data.name;
                                }
                            });
                            return name;
                        }},
                    {field: 'tableName', title: '记录表名', minWidth:100, align:"center",templet:function (d) {
                            if (d.tableName == 'invest') {
                                return '投入品记录'
                            } else if (d.tableName == 'check') {
                                return '检查记录'
                            } else if (d.tableName == 'machining') {
                                return '加工记录'
                            } else if (d.tableName == 'transport') {
                                return '运输记录'
                            } else {
                                //查询自定义表记录
                                var name = '';
                                $.ajax({
                                    url:'/table/' + d.tableName,
                                    type:'GET',
                                    async:false,
                                    success:function (data){
                                        name = data.nameZh;
                                    }
                                });
                                return name;
                            }
                        }},
                    {field: 'remarks', title: '备注', minWidth:100, align:"center"},
                    {title: '操作', minWidth:280, fixed:"right",align:"center",templet:'#tableListBar'}
                ]]
            };
            window.tableIns = table.render(option);
        },
        nodes:null
    };
    //异步加载模板所处场景数据
    $.get("/process/tree/" + request.processTemplateId,function(data) {
        if (data.data.length != 0) {
            data.data[0].spread = true;
        }
        treeData.nodes = data.data;
        layui.tree(treeData);
    });

    /*$.get("/process/tree/" + request.processTemplateId,function (data) {
        $.each(data.data,function (i,ele) {
            var lihtml = '<li class="layui-nav-item layui-nav-itemed">' +
                '<a id="'+ ele.id +'" href="/admin/traceability/record/recordList2?selected='+ ele.id +'&id=' + request.id + '&processTemplateId=' + request.processTemplateId + '&tableType='+ ele.tableType +'"><span>'+ ele.name +'</span></a>';
            //如果存在二级分类
            if (ele.children != null && ele.children.length != 0) {
                lihtml = '<li class="layui-nav-item layui-nav-itemed">' +
                    '<a href="javascript:;"><span>'+ ele.name +'</span></a><dl class="layui-nav-child">';
                $.each(ele.children,function (j, ele) {
                    lihtml += '<dd class=""><a id="'+ ele.id +'"  href="/admin/traceability/record/recordList2?selected='+ ele.id +'&id=' + request.id + '&processTemplateId=' + request.processTemplateId + '&tableType='+ ele.tableType +'"><span class="span-width"></span>'+ ele.name +'</a></dd>';
                });
            }
            lihtml += '</dl></li>';
            $("#process-tree").append(lihtml);
        });
        var innerHtml = '<span class="layui-nav-bar" style="height: 0px; top: 317.5px; opacity: 0;"></span>';
        $("#process-tree").append(innerHtml);

        //重新渲染导航元素
        layui.use('element', function () {
            var element = layui.element;
            var layFilter = $("#process-tree").attr('lay-filter');
            element.render('nav', layFilter);
        });
        $("#" + request.selected).css("color","#1E9FFF");
        $("#" + request.selected).find('span').css({"color":"#1E9FFF"});

        //绑定事件
        $("#process-tree li").click(function () {
            if ($(this).hasClass('layui-nav-itemed')) {
                $(this).addClass('layui-nav-itemed');
            } else {
                $(this).removeClass('layui-nav-itemed');
            }
        });
    });
*/
    //添加二维码
    $(".addBtn").click(function(){
        if (selected != null && selected != '') {
            //隐藏提示信息
            $("#tips").hide();
            var index = layui.layer.open({
                title : "添加二维码（当前生产环节："+ selected.name +"）",
                type : 2,
                content : "recordQrcodeAdd?productBatchId=" + request.id + "&processId=" + selected.id + "&table=" + selected.tableType,
                area: ['100%',$(document).height() + 'px'],
                success : function(layero, index){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回二维码列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize",function(){
                layui.layer.full(index);
            });
        } else {
            layer.msg("请选择左侧生产环节！");
        }

    });


    //列表操作
    table.on('tool(tableList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){
            //打开二维码定制页面
            var index = layui.layer.open({
                title: "编辑二维码信息",
                type: 2,
                content: "recordQrcodeEdit?id=" + data.id,
                area: ['100%',($(document).height() - 40) + 'px'],
                success: function () {
                    setTimeout(function () {
                        layui.layer.tips('点击此处返回', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize", function () {
                layui.layer.full(index);
            });
        }else if(layEvent === 'qrCode') {
            var innerHtml = '<div id="printContent"><div style="text-align: center;padding: 5px;" id="code"></div> ' +
                '<div align="center">备注：'+ data.remarks +'</div>' +
                '<div style="padding: 10px;text-align: center;">' +
                '   <button id="print" class="layui-btn layui-btn-normal">打印</button>' +
                '</div>' +
                '</div>';
            var index = layui.layer.open({
                title : "辅助记录二维码：" + data.name,
                type : 1,
                content : innerHtml,
                area: ['450px','400px'],
                success : function(){
                    $('#code').qrcode(data.requestUrl);

                    //打印事件
                    $("#print").click(function () {
                        $("#printContent").jqprint({
                            debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
                            importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
                            printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
                            operaSupport: true//表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
                        });
                    });
                    setTimeout(function(){
                        layui.layer.tips('点击此处关闭', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500);
                }
            });
        } else if(layEvent === 'edit_default_value') {
            //目标页面
            var targetPage = '';
            if (data.tableName == 'invest' || data.tableName == 'check' || data.tableName == 'machining' ||
                data.tableName == 'transport') {
                //默认的记录添加表
                targetPage = "../qrcode_default_table/"+ data.tableName +"Add?id=" + data.id;
            } else {
                //用户自定义
                targetPage = "../qrcode_default_table/tracerecordAdd?tableName="+ data.tableName +"&id=" + data.id;
            }
            //打开二维码定制页面
            var index = layui.layer.open({
                title: "编辑记录表默认信息",
                type: 2,
                content: targetPage,
                area: ['100%',($(document).height() - 40) + 'px'],
                success: function () {
                    setTimeout(function () {
                        layui.layer.tips('点击此处返回', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize", function () {
                layui.layer.full(index);
            });
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此产品批次？',{icon:3, title:'提示信息'},function(index){
                $.get("/process/qrcode/delete?id=" + data.id,function(data){
                    if (data.code == 200) {
                        layer.msg("删除成功！");
                    } else {
                        layer.msg("删除失败，请重试！");
                    }
                    tableIns.reload();
                    layer.close(index);
                });
            });
        }
    });


    /**
     * 获取路径中的参数
     * @returns {Object}
     */
    function GetRequest() {
        var url = location.search;         //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }

});